<template>
  <div>
    <!-- 开通时，在左侧展示的内容详情-->
    <!-- v-if="formData.aPortData || formData.zPortData" -->
    <div
      class="flex flex-column open-box justify-between"
    >
      <!-- 选中端口信息 -->
      <BaseInfo
        :form-data="formData"
        show-type="open"
        :route-count="routeCount"
        :obtained-count="obtainedCount"
        :route-list="routeList"
        :recommended="recommended"
        @getRouteList="getRouteList('open')"
        @reselect="reselect"
      />
      <div
        v-if="routeList && routeList.length"
        class="route-list-info flex-1 p-5 flex-column overflow-auto"
      >
        <el-radio-group
          v-model="routeSort"
          size="mini"
          class="mr-10"
          @change="sortRouteList"
        >
          <el-radio-button label="linkLength">
            {{ $t('SHORT_LENGTH') }}
          </el-radio-button>
          <el-radio-button label="nodeNum">
            {{ $t('LESS_NODE') }}
          </el-radio-button>
        </el-radio-group>
        <div class="flex-1 overflow-auto">
          <div
            v-for="(item, index) in routeList"
            :key="index"
            class="flex justify-start mb-10 mt-10 top-open-link pointer"
            style="flex-direction: column"
            :class="
              highlightData.routeLinkId === item.routeLinkId
                ? 'topo-open-active'
                : ''"
            @click="showRouteDetail(item)"
          >
            <el-checkbox
              :value="
                item.channelList && item.channelList.some((i) => i.checked)
              "
            >
              {{ $t('RECOMMENDATION') + (index + 1) }}
            </el-checkbox>
            <div class="w-100 pr-10">
              <p>
                {{ $t('TOTAL_CABLE_LENGTH') }}：{{ changeDecimal(item.linkLength || 0, 3, true) }}km；
                {{ $t('NODE_NUM') }}：{{ item.nodeNum - 2 }}
              </p>
              <el-link
                type="primary"
                :underline="false"
                class="white-space-normal"
                @mouseenter.native="mouseEvent(item, 'always')"
                @mouseleave.native="mouseEvent(item, 'leave')"
              >
                {{ $t('INTERMEDIATE_NODE') }}：
                {{ getLinkDetail(item) }}
              </el-link>
            </div>
            <p
              v-if="item.channelList && item.channelList.some((i) => i.checked)"
              class="font-small"
            >
              {{ $t('MOVE_FIBER_DESCRIPTION') }}：
              <span v-html="cutoverDesc(formData.channelData)" />
            </p>
          </div>
        </div>
      </div>
      <!-- 底部按钮 -->
      <div
        class="
      flex
      flex-wrap
      justify-end p-5 pt-0 pb-0 mb-10"
      >
        <div>
          <otdr-test-btn
            v-if="formData.channelData && formData.channelData.length"
            class="w-10"
            :form-data="formData"
            :is-topo="true"
            @taskChange="taskChange"
          />
        </div>
        <div>
          <el-button type="primary" @click="close">
            {{ $t('CANCEL') }}
          </el-button>
          <el-button
            v-if="formData.channelData && formData.channelData.length"
            type="primary"
            @click="next"
          >{{ $t('NEXT') }}</el-button>
        </div>
      </div>
    </div>
    <!-- 链路通道列表详情 -->
    <el-dialog
      v-el-drag-dialog="{updataFull, updataDialogWidth}"
      :fullscreen="isfullscreen"
      :title="$t('INTERMEDIATE_NODE')"
      :visible.sync="routeDetailShow"
      :width="setDialogWidth('1200px')"
      :modal="false"
    >
      <channel-list
        ref="channelList"
        :form-data="formData"
        :show-cutover-list="false"
        :row-data="showRouteData || {}"
        operate-type="open"
      />
      <span slot="footer">
        <el-button
          type="primary"
          @click="closeChannel"
        >{{
          $t('CONFIRM')
        }}</el-button>
      </span>
    </el-dialog>
    <!-- 智能开通 -->
    <component
      :is="openFormShow ? 'OpenForm' : ''"
      ref="OpenForm"
      :dialog-visible.sync="openFormShow"
      @bizOpen="bizOpen"
    />
  </div>
</template>
<script>
  import { mapMutations } from 'vuex'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import { deepClone, checkAfs, changeDecimal } from '@/utils/common'
  import ChannelList from '@/components/ChannelList'
  import OpenForm from './OpenForm'
  import BaseInfo from './BaseInfo'
  import OtdrTestBtn from '@/components/OtdrTestBtn'
  import mixin from '@/mixin/bizFunctionMixin'

  export default {
    components: {
      ChannelList,
      OpenForm,
      OtdrTestBtn,
      BaseInfo
    },
    mixins: [mixin],
    inject: ['functionName', 'parentVM'],
    props: {
      formData: {
        type: Object,
        default: () => {
          return {
            channelData: [],
            routeData: null,
            actionName: 'open'
          }
        }
      }
    },
    data() {
      return {
        changeDecimal: changeDecimal,
        showRouteData: {},
        activeNames: ['main'],
        routeSort: 'linkLength',
        open: 'open',
        routeList: [], // 推荐出来的路由列表
        routeDetailShow: false,
        openFormShow: false,
        transTable: {
          // 传输方向NONE("无"),START("A向"),END("Z向"),DUPLEX("双向");
          NONE: 'NONE',
          SEND: 'A',
          RECEIVE: 'Z',
          SEND_RECEIVE: 'DUPLEX'
        },
        highlightData: {},
        isOtdrTesting: false // 标识otdr是否在进行中
      }
    },
    methods: {
      ...mapMutations(['setGisActived']),
      // 链路信息
      getLinkDetail(data) {
        let linkDetail = ''
        data.segmentList.forEach((i) => {
          linkDetail = linkDetail + i.startNode.nodeName + '-->'
          if (i.cable) {
            linkDetail = linkDetail + i.cable.cableName + '-->'
          }
        })
        return linkDetail + data.endNode.nodeName
      },
      // otdr测试状态改变
      taskChange(data) {
        this.isOtdrTesting = data
        this.$store.commit('setIsOtdrTesting', data)
        if (!data) {
          this.showRouteDetail()
        }
      },
      // 割接信息
      cutoverDesc(arr) {
        const desc = []
        arr.forEach((ele1, index1) => {
          ele1.cutoverList.forEach((ele2, index2) => {
            let str = this.$t('PORT_CONNECT_LINK', {
              msg1: ele2.deviceName,
              msg2: ele2.port.portName,
              msg3: ele2.connPort.portName
            })
            if (index2 === 0 && arr.length === 2) {
              str = '<br>' + this.$t('CHANNEL') + (index1 + 1) + '：' + str
            }
            desc.push(str)
          })
        })
        return desc.join('；') || this.$t('NO_PIPETTING_IS_REQUIRED')
      },
      async next() {
        console.log(this.formData)
        if (this.isOtdrTesting) {
          this.$message.error(this.$t('CONFIRM_OPEN'))
          return
        }
        if (
          !this.formData.routeData ||
          !this.formData.channelData ||
          !this.formData.channelData.length
        ) {
          this.$message.error(this.$t('SELECT_ROUTE_SCHEME'))
          return
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENT_CONNECT')
        if (!checkeAfs) return
        this.openFormShow = !this.openFormShow
      },
      showRouteDetail(data) {
        console.log('路由', data)
        this.showRouteData = data || this.showRouteData
        console.log('this.showRouteData', this.showRouteData)
        if (this.showRouteData.channelList && this.showRouteData.logicMatrix) {
          this.routeDetailShow = true
        } else {
          this.getChannelList(data, 'open')
        }
      },
      async closeChannel() {
        if (
          !this.formData.routeData ||
          !this.formData.channelData ||
          !this.formData.channelData.length
        ) {
          this.$message.error(this.$t('SELECT_ROUTE_SCHEME'))
          return
        }
        // 判断选中的通道AFS设备是否可用
        const checkeAfs = await checkAfs(this.formData, 'INTELLIGENT_CONNECT')
        if (!checkeAfs) return
        this.routeDetailShow = false
      },
      bizOpen(data) {
        const formData = deepClone(this.formData)
        const routeSegmentList = this.formData.routeData.segmentList
        const bizChannelList = formData.channelData.map((i) => {
          const transDirect =
            i.startPortId === formData.aPortData.portId
              ? formData.aPortData.funcType
              : formData.zPortData.funcType
          const cutoverData = i.cutoverList.map((j) => {
            return {
              ...j,
              portName: j.port.bizName,
              connPortName: j.connPort.bizName
            }
          })
          const channelItem = {
            startPortId: i.startPortId,
            endPortId: i.endPortId,
            linkLoss: i.linkLoss,
            cutoverList: cutoverData,
            segmentList: i.segmentList.map((j, jIndex) => {
              return {
                ...j,
                startNode: routeSegmentList[jIndex].startNode,
                endNode: routeSegmentList[jIndex].endNode
              }
            }),
            transDirect: this.transTable[transDirect]
          }
          return channelItem
        })

        console.log('this.formData', this.formData)
        const queryData = {
          bizChannelList: bizChannelList,
          bizOpen: {
            resourceCode: data.resourceCode,
            bizName: data.bizName,
            bizLevel: data.bizLevel,
            endNodeId: formData.zPortData.nodeId,
            endStationId: formData.zPortData.regionId,
            isAutoRestore: false,
            isOtdrTest: false,
            startNodeId: formData.aPortData.nodeId,
            startStationId: formData.aPortData.regionId,
            segmentIdList: formData.routeData.segmentList.map(
              (i) => i.segmentId
            )
          },
          openType: this.formData.routeData.logicMatrix.length > 2 ? 'NORMAL' : 'INDEPENDENT',
          functionName: this.parentVM.functionName // 操作日志需要传此类型，判断是topo还是业务管理里执行的开通
        }
        bizOpenApi.open(queryData).then((res) => {
          if (res) {
            this.$store.commit('changeTicktack')
            this.$message.success(this.$t('ADD_SUCCESS'))
            this.openFormShow = false
            this.$emit('close')
          }
        })
      },
      mouseEvent(data, type) {
        console.log('触发了', data)
        if (data && data.segmentList && data.segmentList.length) {
          const cableIds = []
          const nodeIds = []
          data.segmentList.forEach((i) => {
            if (i.cableId) {
              cableIds.push(i.cableId)
            }
            nodeIds.push(i.endStationId)
            nodeIds.push(i.startStationId)
          })
          if (type === 'always') {
            this.setGisActived({
              cableIds: Array.from(new Set(cableIds)),
              nodeIds: Array.from(new Set(nodeIds)),
              color: 'color-normal'
            })
          } else {
            this.setGisActived({
              cableIds: [],
              nodeIds: [],
              color: ''
            })
          }
        }
      },
      reselect(side) {
        this.formData[side + 'PortData'] = null
        this.formData[side + 'PortData2'] = null
        this.formData[side + 'AfsData'] = null
        this.formData.segmentList = []
        this.formData.channelData = []
        this.formData.routeData = null
        this.recommended = false
        this.routeList = []
      },
      close() {
        this.mouseEvent(this.highlightData, 'leave')
        this.$emit('close')
      }
    }
  }
</script>
<style>
  .el-link {
    word-break: break-all;
  }
  .top-open-link:hover,.topo-open-active {
    background-color: #5050506b;
  }
</style>
